package cn.edu.scau.cmi.limingben.hibernateprog.model.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;

public abstract class HibernateDAO<T> {
    private Session session;

    public void saveOrUpdate(T t) {
        run(() ->
            session.saveOrUpdate(t)
        );
    }

    public void remove(T t) {
        run(() ->
            session.delete(t)
        );
    }
    @SuppressWarnings("unchecked")
    public List<T> listAll() {
        session = HIbernateSessionFactoryUtil.getSession();
        session.beginTransaction();
        List<T> res = (List<T>) session.createQuery("FROM " + getTypeName()).list();
        session.close();
        return res;
    }

    @SuppressWarnings("unchecked")
    protected String getTypeName() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        return ((Class<T>) type.getActualTypeArguments()[0]).getSimpleName();
    }

    protected void run(Runnable runnable) {
        session = HIbernateSessionFactoryUtil.getSession();
        session.beginTransaction();
        runnable.run();
        session.flush();
        session.close();
    }

    protected Session getSession() {
        return HIbernateSessionFactoryUtil.getSession();
    }
}
